<template>
  <!--  已投放列表-->
  <div class="app-container">
    <div class="bg_fff mb_12 pl_14">
      <breadcrumb/>
    </div>
    <div class="content-table">
      <div class="form-content">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
          <el-form-item label="关键词" prop="keyword">
            <el-input
              v-model="queryParams.keyword"
              placeholder="请输入广告计划名称/ID"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="请选择状态"
              clearable
              style="width: 240px"
            >
              <el-option
                v-for="dict in statusList"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>

          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="table-content">
        <div class="table-group">
          <div class="group-left">
            <el-button type="primary" size="mini" @click="selectAll">全选</el-button>
            <el-button type="primary" size="mini" @click="selectInvert">反选</el-button>
          </div>
          <div class="group-right">
            <el-button size="mini" @click="handleViewScheduling()" class="exportBtn" v-hasPermi="['advadvmgtlist:scheduling']">排期</el-button>
            <el-button size="mini" @click="handleExport" class="exportBtn" v-hasPermi="['advadvmgtlist:export']">导出</el-button>
          </div>
        </div>
        <div class="table-big">
          <el-table :data="tableDataList"
                    @selection-change="handleSelectionChange"
                    ref="advergroupTable"
                    :max-height="tableHeight"
                    class="tableHightClass"
          >
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column type="index" width="50" label="序号"/>
            <el-table-column :label="item.label" align="center" v-for="(item,index) in tableColumns" :prop="item.key" v-if="item.visible?item.visible:true" :min-width="item.minWidth?item.minWidth:``" :fixed="item.fixed?item.fixed:false" :show-overflow-tooltip="true">
              <!--用于表格自定义-->
              <template slot-scope="scope">
                <div v-if="item.key=='links'" @click="getLinks(item)" class="links">广告投放链接</div>
                <!--状态-->
                <div v-else-if="item.key=='status'">
                  <el-switch v-model="scope.row[item.key]" @change="handleStatusChange(scope.row)"
                  ></el-switch>
                </div>
                <div v-else-if="item.key=='status_name'" class="status">
                  <span :class="scope.row.status==1? `color-green`:`color-red`">{{ scope.row[item.key] }}</span>
                </div>
                <div v-else>{{ scope.row[item.key] }}</div>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width"
                             width="120">
              <template slot-scope="scope">
                <div class="group-btn">
                  <el-tooltip content="编辑" placement="top" effect="light" v-hasPermi="['advadvmgtlist:edit']">
                    <img src="@/assets/images/tableEdit.png" alt="" @click="handleEdit(scope.row)">
                  </el-tooltip>
                  <el-tooltip content="查看" placement="top" effect="light" v-hasPermi="['advadvmgtlist:view']">
                    <img src="@/assets/images/tableView.png" alt="" @click="handleView(scope.row)">
                  </el-tooltip>


                </div>

              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="total>10"
            :total="total"
            :page.sync="queryParams.page"
            :limit.sync="queryParams.num"
            @pagination="getList"
          />
        </div>

      </div>
    </div>
    <editAdMent v-if="viewEditAdMent" :visableIf.sync="viewEditAdMent" :advertId="advertId" :id="id" :orderId="orderId" @handleQuery="handleQuery"></editAdMent>
    <viewPlanDetails v-if="viewPlanDetails" :visableIf.sync="viewPlanDetails" :advertId="advertId" :id="id" :orderId="orderId"></viewPlanDetails>
    <viewScheduling v-if="viewScheduling" :visableIf.sync="viewScheduling"></viewScheduling>
  </div>

</template>
<script>
import { reqPlanWorkIndex, reqPlanStatusClose, reqPlanStatusOpen, reqGetPlanVersionStatus, reqPlanWorkIndexExport } from '@/api/advergroupPlanMgt/index'

export default {
  name: 'advertisementList',
  components: {
    'editAdMent': () => import('./editAdMent'),
    'viewPlanDetails': () => import('./viewPlanDetails'),
    'viewScheduling': () => import('./viewScheduling')
  },
  data() {
    return {
      // 查询参数
      total: 8,// 表格的总条数
      tableHeight: null,
      id: null,//id
      status: {
        id: []
      },
      queryParams: {
        page: 1,
        num: 10,
        keyword: '',//关键字（广告组名称，id）
        status: null//状态
      },
      statusList: [],//状态集合
      promotionChannelsList: [
        { value: 0, label: '销售线索收集' },
        { value: 1, label: '小程序推广' },
        { value: 2, label: '公众号推广' },
        { value: 3, label: '品牌活动推广' },
        { value: 4, label: '网页推广' }
      ],
      tableDataList: [],//表格数据
      multipleSelection: [],//表格选中的数据

      tableColumns: [
        { key: 'status', label: `状态开关`, visible: true, minWidth: 150 },
        { key: 'plan_order', label: `广告计划ID`, visible: true, minWidth: 150 },
        { key: 'name', label: `广告计划名称`, visible: true, minWidth: 150 },
        { key: 'advert_id', label: `广告组ID`, visible: true, minWidth: 150 },
        { key: 'adName', label: `广告组名称`, visible: true, minWidth: 150 },
        { key: 'plugName', label: `推广方式`, visible: true, minWidth: 150 },
        { key: 'directional', label: `投放版位`, visible: true, minWidth: 150 },
        { key: 'position', label: `用户定向`, visible: true, minWidth: 150 },
        { key: 'custom_coin', label: `投放预算（广告币）`, visible: true, minWidth: 150 },
        { key: 'timeChange', label: `投放排期`, visible: true, minWidth: 150 },
        { key: 'rate_status_name', label: `进度`, visible: true, minWidth: 100 },
        { key: 'mobile', label: `发起人`, visible: true, minWidth: 100 },
        { key: 'status_name', label: `状态`, visible: true, minWidth: 120 },
        { key: 'check_msg', label: `状态原因`, visible: true, minWidth: 120 },
        { key: 'create_time', label: `创建时间`, visible: true, minWidth: 120 },
        { key: 'msg', label: `备注`, visible: true, minWidth: 150 }
      ],
      exportColumns: [
        { key: 'plan_order', label: `广告计划ID` },
        { key: 'name', label: `广告计划名称` },
        { key: 'advertgroup.advert_id', label: `广告组ID` },
        { key: 'advertgroup.name', label: `广告组名称` },
        { key: 'advertgroup.plug_name', label: `推广方式` },
        { key: 'position_name', label: `投放版位` },
        { key: 'direct_diqu', label: `用户定向` },
        { key: 'custom_coin', label: `投放预算（广告币）` },
        { key: 'start_time', label: `投放排期（开始）` },
        { key: 'end_time', label: `投放排期（结束）` },
        { key: 'custom.mobile', label: `发起人` },
        { key: 'status_name', label: `状态`, },
        { key: 'create_time', label: `创建时间` },
        { key: 'msg', label: `备注` }
      ],
      Fields: [],//自定义列表的显示集合
      viewEditAdMent: false,//待审核的编辑控制
      viewPlanDetails: false,//查看计划的代码
      viewScheduling: false,
      scheduleList: [
        { value: 0, label: '待提交' },
        { value: 1, label: '审核中' },
        { value: 2, label: '待投放' },
        { value: 3, label: '投放中' },
        { value: 4, label: '暂停投放' },
        { value: 5, label: '投放结束' }
      ]

    }
  },
  created() {
    this.getList()
    this.getPlanVersionStatus()

  },
  mounted() {
    this.getTabelHeight()//获取表格的最大高度
    this.getTableContentHeight()//获取整体的高度
    window.onresize = () => {
      return (() => {
        this.getTabelHeight()//获取表格的最大高度
        this.getTableContentHeight()//获取整体的高度
        this.$refs.advergroupTable.doLayout()
      })()
    }
  }
  ,
  methods: {
    getPlanVersionStatus() {
      reqGetPlanVersionStatus().then(res => {
        console.log('投放状态', res.data)
        let data = res.data
        for (var key in data) {
          let obj = {
            value: key,
            label: data[key]
          }
          this.statusList.push(obj)//进度状态
        }
      })
    },
    handleStatusChange(row) {
      console.log('状态', row.status)
      let text = row.status == false ? '暂停' : '启用'
      this.$modal.confirm(`确认要${text}广告计划（${row.name}）吗？`).then(function() {
        if (row.status == false) {
          return reqPlanStatusClose(row.id)
        } else {
          return reqPlanStatusOpen(row.id)
        }
      }).then(() => {
        this.$modal.msgSuccess(text + '成功')
        this.getList()
      }).catch(function() {
        row.status = row.status == 1 ? false : true
      })
    },
    getTableContentHeight() {
      let topHeight = document.querySelector('.table-content').offsetTop
      let windowsHeight = document.body.clientHeight
      document.querySelector('.table-content').style.height = windowsHeight - topHeight - 80 + 'px'
    }
    ,
    getTabelHeight() {
      //获取表格的高度
      let topHeight = document.querySelector('.tableHightClass').offsetTop
      let windowsHeight = document.body.clientHeight
      if (this.total > 10) {
        let paginationContainerHeight = document.querySelector('.pagination-container').clientHeight
        this.tableHeight = windowsHeight - topHeight - 20 - paginationContainerHeight - 70
      } else {
        this.tableHeight = windowsHeight - topHeight - 20
      }
    }
    ,

    selectAll() {
      //全选功能,先进行清除状态，然后再选择是全选还是多选
      this.$refs.advergroupTable.clearSelection()
      this.tableDataList.forEach((row) => {
        this.$refs.advergroupTable.toggleRowSelection(row)
      })
    },
    selectInvert() {
      //反选功能
      let listfiter = this.tableDataList.filter(item => {
        return this.multipleSelection.indexOf(item.id) == -1// 不包含选中的
      })
      console.log('反选过滤', listfiter)
      // 然后进行反选
      this.$refs.advergroupTable.clearSelection()
      if (listfiter && listfiter.length > 0) {
        listfiter.forEach((item) => {
          this.$refs.advergroupTable.toggleRowSelection(item)
        })
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = []
      if (val && val.length > 0) {
        val.forEach((item) => {
          this.multipleSelection.push(item.id)
        })
        console.log('multipleSelection', this.multipleSelection)
      }
    },

    getList() {
      this.tableDataList = []
      this.loading = true
      reqPlanWorkIndex(this.queryParams).then(res => {
          this.tableDataList = res.data.list
          this.total = res.data.count
          this.tableDataList.forEach(item => {
            item.adName = item.advertgroup.name//广告组名称
            item.advert_id = item.advertgroup.advert_id//广告组id;
            item.status = item.status == 1 ? true : false
            let plugList = []
            item.advertgroup.plug.forEach(sitem => {
              plugList.push(sitem.plug.name)
            })
            item.plugName = plugList.join(',')//推广渠道
            let positionList = []
            item.planposition.forEach(sitem => {
              positionList.push(sitem.position.name)
            })
            item.directional = positionList.join(',')//投放版位
            let list = []//城市定位
            item.plandirect.forEach(sitem => {
              if (sitem.more && sitem.more.length > 0) {
                sitem.more.forEach(vitem => {
                  let text = ''
                  if (vitem.province && vitem.city && vitem.area) {
                    text = vitem.province + '-' + vitem.city + '-' + vitem.area
                  } else if (vitem.province && vitem.city) {
                    text = vitem.province + '-' + vitem.city
                  } else {
                    text = vitem.province
                  }
                  list.push(text)
                  item.position = list.join(',')//用户定向
                })
              } else {
                let text = ''
                if (!sitem.more) {
                  item.position = '全国'
                } else {
                  if (sitem.more.province && sitem.more.city && sitem.more.area) {
                    text = sitem.more.province + '-' + sitem.more.city + '-' + sitem.more.area
                  } else if (sitem.more.province && sitem.more.city) {
                    text = sitem.more.province + '-' + sitem.more.city
                  } else {
                    text = sitem.more.province
                  }
                  list.push(text)
                  item.position = list.join(',')//用户定向
                }

              }
            })
            if (item.start_time && item.end_time) {
              item.timeChange = item.start_time + '~' + item.end_time//投放排期
            } else if (!item.end_time) {
              item.timeChange = item.start_time
            }
            item.mobile = item.custom.mobile//手机号码

            console.log('item', item)
          })
          this.loading = false
          this.getTabelHeight()//获取表格的最大高度
          this.getTableContentHeight()//获取整体的高度
          this.$refs.advergroupTable.doLayout()
        }
      )
    }
    ,
    //搜索广告计划列表
    handleQuery() {
      this.queryParams.page= 1
      this.getList()
    }
    ,
    //重置表单
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    }
    ,
    //审核
    handleEdit(row) {
      //编辑的方法
      this.advertId = row.advertgroup.id
      this.orderId = row.plan_order
      this.id = row.id
      this.viewEditAdMent = true

    },
    handleView(row) {
      this.advertId = row.advertgroup.id
      this.orderId = row.plan_order
      this.id = row.id
      this.viewPlanDetails = true
    },
    handleViewScheduling() {
      //排期
      this.viewScheduling = true//排期详情

    },
    /** 导出按钮操作 */
    handleExport() {
      let form = JSON.parse(JSON.stringify(this.queryParams))
      let head = []
      let keys = []
      console.log('this.columnsFields', this.columnsFields);
      let text = '投放排期';
      let timeindex = this.tableColumns.findIndex((sitem) => {
        return sitem.label == text;
      });
      console.log('timeindex',timeindex);
      this.exportColumns.forEach(item => {
        this.tableColumns.forEach((sitem, sindex) => {
          if (sitem.label == text) {
            if (head.indexOf(`${text}(开始)`) == -1) {
              head[timeindex] = `${text}(开始)`;
            }
            if (head.indexOf(`${text}(结束)`) == -1) {
              head[timeindex + 1] = `${text}(结束)`;
            }
            if (keys.indexOf('start_time') == -1) {
              keys[timeindex] = 'start_time';
            }
            if (keys.indexOf('end_time') == -1) {
              keys[timeindex + 1] = 'end_time';
            }
          }  else {
            if (sitem.label == item.label) {
              let headIndex = head.findIndex(vitem => {
                return vitem == item.label;
              });
              let keyIndex = keys.findIndex(vitem => {
                return vitem == item.key;
              });
              if (headIndex == -1) {
                if (timeindex < sindex) {
                  head[sindex + 1] = item.label;
                }
                if (timeindex > sindex) {
                  head[sindex] = item.label;
                }

              }
              if (keyIndex == -1) {
                if (timeindex < sindex) {
                  keys[sindex + 1] = item.key;
                }
                if (timeindex > sindex) {
                  keys[sindex] = item.key;
                }

              }
            }
          }

        })
      });
      head = head.filter(item => item);
      keys = keys.filter(item => item);
      form.head = head;
      form.keys = keys;
      delete form.page;
      delete form.num;
      reqPlanWorkIndexExport(form).then((res) => {
        console.log('333', res)
        if (res.code == 1) {
          const a = document.createElement('a')
          document.body.appendChild(a)
          a.download = '已投放列表数据.xls'
          a.href = res.data
          a.click()
          document.body.removeChild(a)
        }

      })

    }

  }
}
</script>
<style lang="scss" scoped>
.app-container {
  .big-title {
    height: 40px;
    border-bottom: 1px solid #D5D5D5;
    background: #fff;
    display: flex;
    align-items: center;
    padding: 0px 24px;
  }

  .form-content {
    padding: 12px;
    background: #fff;
    margin-bottom: 10px;
  }

  /*表格通用代码编写，可用于全局*/
  .table-content {
    background: #fff;
    padding: 0px 15px;

    .table-group {
      display: flex;
      padding: 12px 0px;
      flex-wrap: wrap;

      .group-left {
        width: 200px;
        display: flex;
        flex-wrap: wrap;

        ::v-deep.el-button--primary {
          border: 1px solid #1670F1;
          background: none !important;
          color: #1670F1;
        }
      }

      .group-right {
        flex: 1;
        align-items: center;
        justify-content: flex-end;
        display: flex;

        .suspendBtn {
          background: #FB311E !important;
          border-color: #FB311E;
        }

        .exportBtn, .customStyle {
          border: 1px solid #1670F1;
          background: none !important;
          color: #1670F1;
        }
      }

    }

    /*表格样式*/
    .table-big {
      ::v-deep .el-table {
        .links {
          color: #1670F1;
          text-decoration: underline;
          cursor: pointer;
        }
      }
    }

  }

}

.tableList {
  display: flex;
  border-bottom: 1px solid #eee;
  background: #fff;
  padding: 0px 20px;
  margin: 0;
  height: 54px;
  border-bottom: 10px solid #F8F9FD;
  margin: 16px 0px 0 0px;

  li {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    padding: 0px 10px;
    position: relative;
    cursor: pointer;
    height: 44px;
    color: #8E8E8E;
    margin-right: 30px;

    &.active {
      font-weight: bold;
      color: #000;

      &:after {
        height: 2px;
        background: #1670F1;
        content: '';
        position: absolute;
        left: 10px;
        right: 10px;
        bottom: 0;

      }
    }
  }
}

.status {
  span {
    position: relative;
    padding-left: 15px;

    &:after {
      position: absolute;
      left: 0px;
      width: 9px;
      height: 9px;
      border-radius: 50%;
      content: '';
      top: 50%;
      margin-top: -4.5px;
    }

    &.color-green:after {

      background: #00DD33;


    }

    &.color-red:after {
      background: #D10807;
    }
  }

}
</style>
